import Vue from 'vue'
import store from '../../store' //通过vuex获取token
export default {
	// nicknamea 用户名  不传默认键名 nicknamea
	// imagea 头像 不传默认键名 imagea
	// codea code码 不传默认键名 imagea
	getUserInfo(nicknamea, imagea, codea) { //小程序登录获取=>头像 昵称 code
		let nickname = nicknamea ? nicknamea : 'nickname'
		let image = imagea ? imagea : 'image'
		let code = codea ? codea : 'code'
		return new Promise((resolve, reject) => {
			uni.getUserProfile({
				lang: 'zh_CN',
				desc: '登录',
				success: res => {
					uni.login({
						provider: 'weixin',
						success: loginRes => {
							let obj = {
								[nickname]: res.userInfo.nickName,
								[image]: res.userInfo.avatarUrl,
								[code]: loginRes.code,
							}
							resolve(obj)
						}
					});
				},
				fail: err => {
					console.log(err);
					reject(err)
				}
			});
		})
	},

	//小程序获取位置信息
	getAddressWx(type = 'scope.userLocation') { //小程序获取位置  //scope.userLocation精准位置 scope.userFuzzyLocation模糊未知
		return new Promise((resolve, reject) => {
			// reject(err)
			uni.getSetting({
				success: res => {
					// console.log('用户权限列表:', res.authSetting) 
					if (res.authSetting[type]) {
						// console.log('已授权userLocation')
						this.getAddressWxCicy(type).then(resa => {
							// console.log(resa,888);
							resolve(resa)
						}).catch(err => {
							reject(err)
						})
					} else {
						// console.log('用户未授权userLocation')
						//2.用户第一次进来发起授权
						uni.authorize({
							scope: type,
							success: (res1) => {
								// console.log("允许授权", res1);
								// 3.如果用户点击了允许，调用选择位置信息函数选择位置
								this.getAddressWxCicy(type).then(resa => {
									resolve(resa)
								}).catch(err => {
									reject(err)
								})
							},
							fail: (err1) => {
								// console.log("拒绝授权", err1);
								// 3.如果用户点击了拒绝或者用户之前点击过拒绝授权，打开用户设置模态框
								uni.showModal({
									title: '',
									content: '获取定位失败，是否授权打开定位',
									success: (res) => {
										if (res.confirm) {
											this.openSetting(type).then(
												resa => {
													resolve(resa)
												}).catch(err => {
												reject(err)
											})
										} else if (res.cancel) {
											uni.$u.toast('拒绝定位，可能导致功能异常')
										}
									}
								})
							},
						})
					}
				}
			})
		})
	},

	openSetting(type) { //引导用户打开位置权限
		return new Promise((resolve, reject) => {
			uni.openSetting({
				success: (res) => {
					// console.log("打开设置成功", res);
					if (res.authSetting[type]) {
						// console.log('成功授权userLocation')
						// 5.用户在设置中点击了允许，调用选择位置信息函数
						this.getAddressWxCicy(type).then(resa => {
							resolve(resa)
						}).catch(err => {
							reject(err)
						})
					} else {
						// console.log('用户未授权userLocation')
						// 5.用户在设置中点击了不允许，展示拒绝授权信息
						uni.$u.toast('拒绝定位，可能导致功能异常')
					}
				},
				fail: (err) => {
					console.log("打开设置失败", err)
				}
			})
		})
	},

	getAddressWxCicy(type) { //已授权获取位置信息
		return new Promise((resolve, reject) => {
			if (type == 'scope.userLocation') {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						// console.log(res);
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				})
			} else if (type == 'scope.userFuzzyLocation') {
				uni.getFuzzyLocation({
					type: 'wgs84',
					success: (res) => {
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				})
			}
		})
	},

	getProvinces(longitude, latitude) { //根据经纬度反编码获取地址信息 - 高德
		return new Promise((resolve, reject) => {
			uni.request({
				url: `https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=${longitude},${latitude}&key=2bc840e45eed909bc022753d4cf324b3`,
				method: 'GET',
				timeout: 10000,
				success: (resb) => {
					// console.log(resb, 888);
					if (resb.data.status == 1) {
						resolve(resb.data.regeocode)
					} else {
						uni.$u.toast('请输入正确的经纬度')
					}
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},
	getProvincesTencent(longitude, latitude) { //根据经纬度反编码获取地址信息 - 腾讯
		return new Promise((resolve, reject) => {
			uni.request({
				url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=OHMBZ-45FKB-DXJU5-NVWXD-R7BSO-WUFJF&get_poi=1`,
				method: 'GET',
				timeout: 10000,
				success: (res) => {
					// console.log(res, 888);
					if (res.data.status == 0) {
						resolve(res.data.result)
					} else {
						uni.$u.toast('请输入正确的经纬度')
					}
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},

	//蓝牙
	getBluetooth() { //小程序获取蓝牙权限
		return new Promise((resolve, reject) => {
			uni.getSetting({
				success: res => {
					if (res.authSetting['scope.bluetooth']) {
						resolve(res)
					} else {
						//用户第一次进来发起授权
						uni.authorize({
							scope: 'scope.bluetooth',
							success: (resa) => {
								// console.log("允许授权", resa);
								// 如果用户点击了允许
								resolve(resa)
							},
							fail: (err) => {
								// console.log("拒绝授权", err1);
								// 3.如果用户点击了拒绝或者用户之前点击过拒绝授权，打开用户设置模态框
								uni.showModal({
									title: '',
									content: '获取蓝牙权限失败，是否授权蓝牙权限',
									success: (res) => {
										if (res.confirm) {
											this.openSettingBluetooth()
												.then(
													resa => {
														resolve(resa)
													}).catch(err => {
													reject(err)
												})
										} else if (res.cancel) {
											uni.$u.toast('拒绝蓝牙权限，会导致功能异常')
										}
									}
								})
							},
						})
					}
				}
			})
		})
	},

	openSettingBluetooth() { //引导用户打开蓝牙权限
		return new Promise((resolve, reject) => {
			uni.openSetting({
				success: (res) => {
					// console.log("打开设置成功", res);
					if (res.authSetting['scope.bluetooth']) {
						// 用户在设置中点击了允许
						resolve(res)
					} else {
						// console.log('用户未授权userLocation')
						// 5.用户在设置中点击了不允许，展示拒绝授权信息
						uni.$u.toast('拒绝蓝牙权限，会导致功能异常')
					}
				},
				fail: (err) => {
					console.log("打开设置失败", err)
				}
			})
		})
	},

	//订阅消息通知
	getSubscribeMsg(tmplId) { //小程序获订阅权限
		return new Promise((resolve, reject) => {
			uni.getSetting({
				withSubscriptions: true,
				success: res => {
					// console.log(res, '==');
					if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
						if (res.subscriptionsSetting.mainSwitch && !res.subscriptionsSetting
							.itemSettings) {
							this.openSettingSubscribeMsg(tmplId).then(resb => {
								resolve(resb)
							})
						} else if (res.subscriptionsSetting.mainSwitch && res.subscriptionsSetting
							.itemSettings) {
							if (res.subscriptionsSetting.itemSettings) {
								let item = res.subscriptionsSetting.itemSettings[tmplId]
								if (item == 'reject') {
									// console.log('提示：用户拒绝订阅消息')
									wx.showModal({
										title: '订阅消息',
										content: '您当前拒绝接受消息通知，是否去开启',
										success(resb) {
											if (resb.confirm) {
												// console.log('用户点击确定')
												wx.openSetting({
													success(resc) {
														resolve(resc)
													},
													fail(err) {
														//失败
														resolve(resc)
														// console.log(err)
													}
												})
											} else if (resb.cancel) {
												resolve(resb)
												// console.log('用户点击取消')
											}
										}
									})
								} else if (item == 'accept') {
									// console.log('提示：您已经开启订阅消息')
									this.openSettingSubscribeMsg(tmplId).then(resb => {
										resolve(resb)
									})
								} else if (item == 'ban') {
									// console.log('提示：您已经被后台封禁')
								}
							}
						} else {
							// console.log('提示：用户没有勾选订阅消息或者没有状态')
							this.openSettingSubscribeMsg(tmplId)
						}
					}
				}
			})
		})
	},

	openSettingSubscribeMsg(tmplId) { //获取用户订阅
		return new Promise((resolve, reject) => {
			wx.requestSubscribeMessage({
				tmplIds: [tmplId],
				success: resa => {
					resolve(resa)
					// if (resa[tmplId] === 'accept') {
					// 	resolve(resa)
					// } else if (resa[tmplId] == 'reject') {
					// 	console.log('取消');
					// 	resolve(resa)
					// }
				},
				fail(err) {
					//失败
					reject(err)
				}
			})
		})
	},


	//保存图片
	// url 图片的路径
	// isPath 是否需要通过uni.getImageInfo获取本地图片
	// fileType 默认image保存图片 video保存视频
	// isProgress 是否显示下载进度


	// async saveCodeImg() { //保存多张图片
	// 	for (let i = 0; i < this.list.length; i++) {
	// 		this.list[i]
	// 		await wxApplet.dowLoadImg(this.list[i])
	// 	}
	// },

	dowLoadImg(url, isPath = true, fileType = 'image', isProgress = true) { //判断保存图片视频权限
		return new Promise((resolve, reject) => {
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success: (res) => {
					this.saveImgWx(url, isPath, fileType, isProgress)
				},
				fail: err => {
					uni.getSetting({
						success: (res) => {
							// console.log(res.authSetting)
							if (!res.authSetting['scope.writePhotosAlbum']) {
								this.opensit(url, isPath, fileType, isProgress)
							}
						}
					})
				},
			})
		})

	},
	opensit(url, isPath, fileType, isProgress) {
		uni.showModal({
			content: fileType == 'image' ? '是否授权小程序保存图片到相册？' : '是否授权小程序保存视频到相册？',
			confirmText: '授权',
			success: (res) => {
				if (res.confirm) {
					uni.openSetting({
						success: (res) => {
							// console.log(res.authSetting)
							this.saveImgWx(url, isPath, fileType, isProgress)
						},
					})
				} else if (res.cancel) {
					// uni.$u.toast('授权失败')
				}
			},
		})
	},
	saveImgWx(url, isPath, fileType, isProgress) { //已授权保存相册 小程序
		if (isPath) {
			if (fileType == 'image') {
				uni.getImageInfo({
					src: url,
					success: (res) => {
						this.saveWxFile(res.path, fileType)
					},
					fail: (err) => {
						// console.log(err);
						uni.$u.toast('网络错误请重试')
					}
				});
			} else if (fileType == 'video') {
				const downloadTask = uni.downloadFile({
					url: url,
					success: (res) => {
						if (res.statusCode === 200) {
							// console.log('下载成功');
							this.saveWxFile(res.tempFilePath, fileType)
						} else {
							uni.$u.toast('网络错误请重试')
						}
					},
					fail: (err) => {
						// console.log(err);
						uni.$u.toast('网络错误请重试')
					}
				});

				downloadTask.onProgressUpdate((res) => {
					// console.log(res);
					if (res.progress > 0) {
						if (isProgress) {
							uni.showLoading({
								title: `下载${res.progress}%`
							})
							if (res.progress == 100) {
								uni.hideLoading();
							}
							setTimeout(() => {
								uni.hideLoading();
							}, 1000 * 60 * 2)
						}
					}
					// console.log('下载进度：' + res.progress);
					// console.log('已下载长度：' + res.totalBytesWritten);
					// console.log('文件总长度：' + res.totalBytesExpectedToWrite);
				})
			}
		} else {
			this.saveWxFile(url, fileType)
		}
	},
	saveWxFile(url, fileType) { //保存视频或图片
		if (fileType == 'image') {
			uni.saveImageToPhotosAlbum({
				filePath: url,
				success: () => {
					uni.$u.toast('保存成功')
				},
				fail: () => {
					uni.$u.toast('保存失败')
				}
			});
		} else if (fileType == 'video') {
			uni.saveVideoToPhotosAlbum({
				filePath: url,
				success: () => {
					uni.$u.toast('保存成功')
				},
				fail: () => {
					uni.$u.toast('保存失败')
				}
			});
		}
	},

	uploadImg(num = 3, size, isTailor = false) { //上传图片
		//sizeType：['original', 'compressed'] original：原图 compressed：压缩图 isTailor:是否裁剪(适用于单图上传) size:图片上传大小限制
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: num,
				success: (res) => {
					this.disposeImg(res.tempFiles, size, isTailor).then(resa => {
						resolve(resa)
					})
				},
				fail: (err) => {
					reject(err)
				},
			})
		})
	},

	disposeImg(images, size, isTailor) { //处理图片 解决异步问题
		return new Promise((resolve, reject) => {
			let promiseArr = images.map(async (item) => {
				if (size && (item.size / 1024 / 1024) > size) {
					uni.$u.toast('图片超过大小')
					return
				} else {
					if (isTailor) {
						let img_url = await this.tailorImg(item.path)
						let img_urla = await this.uploadFile(img_url)
						return img_urla
					} else {
						let img_url = await this.uploadFile(item.path)
						return img_url
					}
				}
			})

			Promise.all(promiseArr).then((res) => {
				resolve(res)
			})
		})
	},
	tailorImg(e) { //裁剪图片
		return new Promise((resolve, reject) => {
			wx.cropImage({
				src: e, // 图片路径
				cropScale: '1:1', // 裁剪比例
				success: (res) => {
					resolve(res.tempFilePath)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	},

	uploadFile(file, isToken = true) { //上传图片
		return new Promise((resolve, reject) => {
			uni.showLoading({
				title: '上传中...'
			})
			uni.uploadFile({
				url: `${Vue.prototype.$http}${Vue.prototype.$uploadUrl}`, //仅为示例，非真实的接口地址
				filePath: file,
				name: 'file',
				header: {
					'token': store.state.token
				},
				success: (res) => {
					let data = JSON.parse(res.data)
					resolve(data)
				},
				fail: (err) => {
					reject(err)
				},
				complete: () => {
					uni.hideLoading()
				}
			});
		})
	},

	previewImage(e, num = 1) { //预览图片
		let arr = Array.isArray(e) ? e : e.split(',')
		uni.previewImage({
			current: num,
			urls: arr,
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: (data) => {
					console.log(data);
				},
				fail: (err) => {
					console.log(err);
				}
			}
		});
	},

	wxPay(e) { //微信小程序支付
		return new Promise((resolve, reject) => {
			uni.requestPayment({
				provider: "wxpay",
				timeStamp: e.timeStamp,
				nonceStr: e.nonceStr,
				package: e.package,
				signType: e.signType,
				paySign: e.paySign,
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				}
			});
		})
	},
}